package com.comleader.uap.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;

import com.alibaba.fastjson.JSON;
import com.comleader.uap.common.response.Result;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @Dscription
 * @Author 连新景
 * @Date 2024/11/27 11:16
 */
@Slf4j
public class ResponseUtil {

    public static void write(HttpServletResponse response, Result<?> result) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(JSON.toJSONString(result));
    }

    public static void setDownloadFileHeader(HttpServletResponse response, String fileName) {
        response.setCharacterEncoding("utf-8");
        try {
            if (StrUtil.isNotBlank(fileName)) {
                response.setHeader(HttpHeaders.CONTENT_TYPE,
                    MediaTypeFactory.getMediaType(fileName).orElse(MediaType.APPLICATION_OCTET_STREAM) + ";charset=utf-8");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"));
                response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
            }
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }
}
